package 笔记.多线程;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author CHL
 * @ClassName: LockDemo
 * @Description: TODO
 * @date 2025/10/18 22:37
 * @Version 1.0
 */
@Slf4j
public class LockDemo {


    public static void main(String[] args) throws InterruptedException {


        // 锁升级
      /*  Demo user = new Demo();
        // mackWord 对象头 HotSpot虚拟机的对象头包含两部分信息，第一部分是mackWord,用于存储自身运行的数据，如：哈希码、GC分代年龄、锁状态标志、线程持有
        System.out.println("无状态001:" + ClassLayout.parseInstance(user).toPrintable());


        // JVM默认延时4秒后开启偏向锁 可通过 XX:BiasedLockingStartupDelay=0 取消延时；
        // 如果不要偏向锁，可通过 -XX:-UseBiasedLocking = false 来设置
        // 自JDK15以后偏向锁默认禁用，需手动启用 -XX:+DisableBiasedLocking
        Thread.sleep(5000);

        Demo demo = new Demo();
        System.out.println("启用偏向锁101:" + ClassLayout.parseInstance(demo).toPrintable());


        for (int i = 0; i < 2; i++) {
            synchronized (demo) {
                System.out.println("偏向锁101+带线程ID:" + ClassLayout.parseInstance(demo).toPrintable());
            }
            System.out.println("偏向锁释放101+带线程ID:" + ClassLayout.parseInstance(demo).toPrintable());
        }

        new Thread(() -> {
            synchronized (demo) {
                System.out.println("升级轻量级锁00:" + ClassLayout.parseInstance(demo).toPrintable());

                try {
                    System.out.println("线程睡觉3秒钟------------");
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("轻量级锁升级重量锁10:" + ClassLayout.parseInstance(demo).toPrintable());
            }

        }).start();

        // 再起个线程确认重量级锁
        new Thread(() -> {
            synchronized (demo) {
                System.out.println("重量级锁10:" + ClassLayout.parseInstance(demo).toPrintable());
            }
        }).start();*/


        // 锁自旋
        AtomicInteger atomicInteger = new AtomicInteger();
        while (true){
            int oldValue = atomicInteger.get();
            int newValue = oldValue + 1;
            if (atomicInteger.compareAndSet(oldValue, newValue)){  //CAS 数据交换一致性
                break;
            }

        }

        // 分段CAS机制，防止大量的线程自旋，高占用CPU
        LongAdder longAdder= new LongAdder();
        longAdder.increment(); // +1操作

        // 主内存的值自动求和
        longAdder.sum();
    }
}
